<template>
    <div class="container auth-container">
        <div class="operation-wrapper">
            <el-button
                type="primary"
                size="mini"
                :disabled="!authResult.auth_edit"
                @click="submitAuth">保存</el-button>
        </div>
        <div class="panel-wrapper">
            <div
                class="panel"
                v-for="(item, index) in resolveList"
                :key="index">
                <div class="panel-header">
                    <div class="panel-title-wrapper">
                        <span class="panel-title">{{ item.title }}</span>
                    </div>
                    <div
                        class="panel-header-operation"
                        v-if="item.group_no == 'not_sorted'"
                        @click="dialogVisible = true"
                        style="color: #6f7180;cursor:pointer">
                        <span>移动</span>
                        <el-icon name="edit-outline" />

                    </div>
                </div>
                <div class="panel-content">
                    <template v-if="item.group_no !== 'not_sorted'">
                        <el-tree
                            v-if="item.children"
                            :data="item.children"
                            :props="{label: 'title'}"
                            draggable
                            @node-drop="handleDropEnd"
                            :allow-drag="handleIsAllowDrag"
                            :allow-drop="handleIsAllowDrop"/>
                    </template>
                    <template v-else>
                        <el-tree
                            v-if="item.children"
                            :data="item.children"
                            :props="{label: 'title'}"/>
                    </template>
                </div>
            </div>
        </div>
        <el-dialog
            title="设置未分组权限"
            :visible.sync="dialogVisible"
            @close="transferTargetList=[]">
            <el-form>
                <el-form-item label="请选择目标分组">
                    <el-select
                        v-model="transferTarget"
                        placeholder="请选择">
                        <el-option
                            v-for="item in topLevelGroupList"
                            :key="item.group_no"
                            :label="item.title"
                            :value="item.group_no"/>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-transfer
                v-model="transferTargetList"
                :data="notSortedAuthList"
                :titles="transferTitles"
                :props="{key: 'auth_name', label: 'title'}"/>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button
                    type="primary"
                    @click="handleTransfer">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { addAuthToGroup, extractAuth } from "@/assets/js/transform";

export default {
    data() {
        return {
            authResult: {},
            authGroupList: [], // 权限分组原始数据
            authList: [], // 权限原始数据
            resolveList: [], // 权限及分组融合后的列表，用于渲染页面使用
            notSortedAuthList: [], // 未分组权限
            transferSourceList: [], // 穿梭框原数据
            transferTargetList: [], // 已选中穿梭框数据
            transferTarget: '', // 穿梭框用，目标列表 group_no
            topLevelGroupList: [], // 一级分组列表，穿梭框使用
            dialogVisible: false
        };
    },
    computed: {
        transferTitles() {
            let target;

            for (let i in this.topLevelGroupList) {
                if (this.topLevelGroupList[i].group_no == this.transferTarget) {
                    target = this.topLevelGroupList[i].title;
                }
            }
            return ['未分组', target || '上方选择分组'];
        }
    },
    created() {
        this.$store.commit('SET_HEADER', [
            {
                title: '设置',
            },
            {
                title: '权限列表'
            }
        ]);
        this.authResult = this.$route.meta.authResult;
        this.init();
    },
    methods: {
        /**
         * 初始化
         */
        init() {
            this.getAuthGroup(() => {
                this.getAuthList();
            });
        },

        /**
         * 获取权限分组
         */
        getAuthGroup(callback) {
            this.$post('/__local/system%5Cauth_group%5Cget_list', {}, resp => {
                if (resp.code == 1) {
                    if (Array.isArray(resp.data.list)) {
                        this.authGroupList = resp.data.list;
                    } else {
                        this.groupList = [];
                    }
                    if (callback) {
                        callback();
                    }
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg || '获取权限分组失败，请刷新重试'
                    });
                }
            });
        },

        /**
         * 获取权限
         */
        getAuthList() {
            this.$post('/__local/system%5Cauth%5Cget_list', {}, resp => {
                if (resp.code == 1) {
                    this.authList = resp.data.list;

                    let group = [].concat(this.authGroupList);
                    let auth = [].concat(this.authList);
                    let { resolve, left } = addAuthToGroup(group, auth);

                    for (let i in resolve) {
                        let { group_no, title } = resolve[i];

                        this.topLevelGroupList.push({
                            group_no,
                            title
                        });
                    }

                    resolve.push({
                        create_time: 0,
                        title: '未分组',
                        prarent_group_no: '',
                        group_no: 'not_sorted',
                        children: left
                    });
                    console.log(resolve);

                    this.resolveList = resolve;
                    this.notSortedAuthList = left;
                    // this.transferSourceList = [].concat(left);
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg || '获取权限列表失败，请刷新重试'
                    });
                }
            });
        },

        /**
         * 移动未分类权限
         */
        handleTransfer() {
            if (!this.transferTarget) {
                this.$message({
                    type: 'warning',
                    message: '请先选择目标分组'
                });
                return;
            }
            if (this.transferTargetList.length == 0) {
                this.$message({
                    type: 'warning',
                    message: '未选中未分组的权限'
                });
                return;
            }

            // 向目标分组添加数据以及删除穿梭框及未分类界面显示中的数据
            let arr = [];

            for (let i = 0, len = this.transferTargetList.length; i < len; i++) {
                for (let j = 0, jlen = this.notSortedAuthList.length; j < jlen; j++) {
                    if (this.notSortedAuthList[j] && (this.notSortedAuthList[j].auth_name == this.transferTargetList[i])) {
                        let item = this.notSortedAuthList.splice(j, 1);

                        item[0].group_no = this.transferTarget;
                        arr.push(item);
                        j--;
                    }
                }
            }
            for (let i in this.resolveList) {
                if (this.resolveList[i].group_no == this.transferTarget) {
                    this.$set(this.resolveList[i], 'children', this.resolveList[i].children.concat(...arr));
                }
            }

            this.dialogVisible = false;
        },

        /**
         * 拖动结束事件
         */
        handleDropEnd(node, target, type, e) {
            if (target.data.children) {
                node.data.group_no = target.data.group_no;
            }
        },

        /**
         * 提交数据
         */
        submitAuth() {
            let arr = extractAuth(this.resolveList);

            this.$post('/__local/system%5Cauth%5Cset_auth_group', {
                data: JSON.stringify(arr)
            }, resp => {
                if (resp.code == 1) {
                    this.init();
                    this.$message({
                        type: 'success',
                        message: '设置成功'
                    });
                }
            });
        },

        /**
         * 判断是否可以被移动
         */
        handleIsAllowDrag(node) {
            if (node.data.children) {
                return false;
            }
            return true;
        },

        /**
         * 判断是否允许被放置
         */
        handleIsAllowDrop(draggingNode, dropNode, type) {
            if (dropNode.data.auth_name && type == 'inner') {
                return false;
            }
            return true;
        }
    }
};
</script>

<style lang="less" scoped>
.auth-container {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.operation-wrapper {
    display: flex;
    flex-direction: row-reverse;
    padding: 12px 23px;
    background-color: #fff;
}
.panel-wrapper {
    flex: 1;
    padding: 15px;
    font-size: 0;
    white-space: nowrap;
    overflow-x: auto;
    overflow-y: hidden;
}
.panel {
    position: relative;
    display: inline-block;
    width: 345px;
    height: 100%;
    margin-right: 20px;
    padding-top: 45px;
    font-size: 14px;
    background-color: #fff;
    border-radius: 2px;
    border: 1px solid #ebebeb;
    vertical-align: top;
}
.panel-header {
    position: absolute;
    top: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 15px;
    line-height: 45px;
    background-color: #f7f7f7;
}
.panel-content {
    height: 100%;
    padding: 20px;
    overflow: auto;
}
</style>

<style lang="less">
.auth-container {
    .el-tree-node__content {
        height: auto!important;
    }
}
</style>
